package com.wxmit.framework.web.handler;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.SaTokenException;
import cn.hutool.core.collection.CollUtil;
import com.wxmit.base.constant.HttpStatus;
import com.wxmit.base.domain.ApiResult;
import com.wxmit.base.exception.BaseException;
import com.wxmit.framework.excel.exception.ExcelReadValidException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description 全局异常处理
 * @Author huangxiong
 * @Date 2022/7/11 15:03
 * @Version V1.0
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ApiResult exception(Exception e)
    {
        log.error(e.getMessage(), e);
        return ApiResult.fail("未知异常，请联系管理员！");
    }

    @ExceptionHandler(BaseException.class)
    public ApiResult exception(BaseException e)
    {
        log.error(e.getMessage(), e);
        return ApiResult.fail(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ApiResult illegalArgumentException(IllegalArgumentException e){
        return ApiResult.fail(e.getMessage());
    }


    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResult<Map<String,Object>> validExceptionHandler(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        Map<String, Object> errorMap = fieldErrors.stream()
                .collect(Collectors.toMap(FieldError::getField, item -> Objects.isNull(item.getDefaultMessage())?"校验异常":item.getDefaultMessage()));
        return ApiResult.fail(errorMap,"校验异常");
    }

    @ExceptionHandler(ExcelReadValidException.class)
    public ApiResult<List<ExcelReadValidException.ValidError>>  excelReadValidException (ExcelReadValidException e){
        String msg = CollUtil.isEmpty(e.getList())?e.getMessage():CollUtil.join(e.getList()," ; ");
        return  ApiResult.fail(e.getList(),msg);
    }

    @ExceptionHandler(SaTokenException.class)
    public ApiResult saTokenException(SaTokenException e){
        return ApiResult.fail(e.getMessage());
    }

    @ExceptionHandler(NotPermissionException.class)
    public ApiResult notPermissionException(NotPermissionException e){
        return ApiResult.failWithCode(HttpStatus.UNAUTHORIZED,"权限不足");

    }

    @ExceptionHandler(NotLoginException.class)
    public ApiResult notLoginException(NotLoginException e){
        return ApiResult.failWithCode(HttpStatus.FORBIDDEN,"登陆状态失效，请重新登陆！");
    }

}
